<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>

        <span>|</span>

        <span>{{ id?'编辑企业':'添加企业' }}</span>

      </div>

      <div class="right">
        黑马程序员
      </div>

    </header>

    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>

        <div class="form">
          <el-form ref="ruleForm" label-width="100px" :model="addForm" :rules="addFormRules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>

            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>

            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>

            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :value="item.industryCode"
                  :label="item.industryName"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>

            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>

            <el-form-item label="营业执照" prop="businessLicenseId">
              <!--
              http-request：覆盖默认的上传行为，可以自定义上传的实现
              file-list：上传的文件列表 filelist是数组
              action：必选参数，上传的地址
              before-upload：上传文件之前的钩子，参数为上传的文件 若返回false则停止上传
                -->
              <el-upload
                :before-upload="beforeupload"
                action="#"
                :http-request="uploadRequest"
                :file-list="filelist"
                :limit="1"
                :on-exceed="exceed"
                :on-remove="remove"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
          </el-form>

        </div>

      </div>

    </main>

    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>

        <el-button type="primary" @click="createEnterprise">确定</el-button>

      </div>

    </footer>

  </div>

</template>

<script>
import { getIndustryListAPI, uploadAPI, createEnterpriseAPI, dataEnterpriseAPI, editEnterpriseAPI } from '@/api/enterprise'
export default {
  data() {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      //   所在行业列表
      industryList: [],
      //   校验
      addFormRules: {
        name: [
          { required: true, message: '请输入企业名称', tigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '请输入法人', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '请输入注册地址', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '请输入所在行业', trigger: 'change' }
        ],
        contact: [
          { required: true, message: '请输入企业联系人', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '请输入联系人电话', trigger: 'blur' }
        ],
        businessLicenseId: [
          { required: true, message: '请输入营业执照', trigger: 'change' }
        ]
      },
      filelist: [],
      title: '添加信息'
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  mounted() {
    this.getIndustryList()
  },
  async created() {
    if (this.id) {
    //  在渲染dom之前回填数据
      const { data } = await dataEnterpriseAPI(this.id)
      // console.log(data)
      this.addForm.name = data.name
      this.addForm.legalPerson = data.legalPerson
      this.addForm.registeredAddress = data.registeredAddress
      this.addForm.industryCode = data.industryCode
      this.addForm.contact = data.contact
      this.addForm.contactNumber = data.contactNumber
      this.addForm.businessLicenseUrl = data.businessLicenseUrl
      this.addForm.businessLicenseId = data.businessLicenseId
      this.filelist = [{ name: data.businessLicenseName, url: data.businessLicenseUrl }]
    }
  },
  methods: {
    // 向后端发送请求 进行下拉框渲染
    async getIndustryList() {
      const { data } = await getIndustryListAPI()
      //   console.log(data)
      this.industryList = data
    },
    // 上传文件的校验
    beforeupload(file) {
      // 规定文件后缀名
      const accessTypeList = ['image/png', 'image/jpg', 'image/jpeg']
      //   规定文件大小
      const maxSize = 2 * 1024 * 1024
      //   类型校验是否通过
      const fileflag = accessTypeList.includes(file.type)
      //   文件类型校验是否通过
      if (!fileflag) {
        this.$message.error('只能上传png、jpg、jpeg文件')
      }
      //   文件大小校验是否通过
      const sizeflag = file.size <= maxSize
      if (!sizeflag) {
        this.$message.error('文件不能超过5MB')
      }
      return fileflag && sizeflag
    },
    // 上传文件
    async uploadRequest(data) {
      const formData = new FormData()
      // 往数组或者对象里面添加元素
      // 添加文件
      formData.append('file', data.file)
      // 文件类型
      formData.append('type', 'businessLicense')
      // 调用接口
      const res = await uploadAPI(formData)
      //   console.log(res)
      this.addForm.businessLicenseId = res.data.id
      this.addForm.businessLicenseUrl = res.data.url
      // 手动校验
      this.$refs.ruleForm.validate(valid => {
        console.log(valid)
      })
    },
    exceed(files, fileList) {
      this.$message.warning('文件超出个数限制')
    },
    remove(files, fileList) {
    // 重置表单
      this.addForm.businessLicenseUrl = ''
      this.addForm.businessLicenseId = ''
    },
    // 新增企业
    async createEnterprise() {
      // 校验
      this.$refs.ruleForm.validate(async valid => {
        // console.log(valid)
        if (valid) {
          // 判断有无id 有id是编辑 无id是新增
          if (!this.id) {
            // 新增
          // 调接口
            const res = await createEnterpriseAPI(this.addForm)
            console.log(res)
            if (res.code === 10000) {
              this.$message.success('新增成功')
              this.$router.back()
            } else {
              this.$message.error('新增失败')
            }
          } else {
            //  编辑
            // 回填数据
            await editEnterpriseAPI({ ...this.addForm, id: this.id })
            // 操作成功的提示信息
            this.$message.success('操作成功')
            // 返回上一级页面
            this.$router.back()
          }
        }
      })
    }
  }
}
</script>

  <style scoped lang="scss">
  .add-enterprise {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
      display: flex;
      justify-content: space-between;
      padding: 0 20px;
      height: 64px;
      line-height: 64px;
      font-size: 16px;
      font-weight: bold;
      background-color: #fff;

      .left {
        span {
          margin-right: 4px;
        }
        .arrow{
          cursor: pointer;
        }
      }

      .right {
        text-align: right;
      }
    }

    .add-main {
      background: #f4f6f8;
      padding: 20px 130px;

      .form-container {
        background-color: #fff;
        .title {
          height: 60px;
          line-height: 60px;
          padding-left:20px;
        }
        .form {
          margin-bottom: 20px;
          padding: 20px 65px 24px;
          .el-form{
            display: flex;
            flex-wrap: wrap;
            .el-form-item{
              width: 50%;
            }
          }
        }
      }
    }

    .add-footer {
      position: fixed;
      bottom: 0;
      width: 100%;
      padding: 24px 50px;
      color: #000000d9;
      font-size: 14px;
      background: #fff;
      text-align: center;
    }
  }
  </style>
